package com.wstuo.common.customForm.util;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.log4j.Logger;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.util.CycleDetectionStrategy;

import com.wstuo.common.tools.service.BaseTools;

public class FormCustomUtil {
	final static Logger LOGGER = Logger.getLogger(FormCustomUtil.class);
	private static JsonConfig jsonConfig = new JsonConfig();

	/**
	 * 将数据库中的表单内容进行解析 生成导入文件的表头
	 * @param formContent
	 * @param exclude
	 * @param separator
	 * @return
	 */
	public static String[] decodeFrom(String formContent,Set<String> exclude
			,Map<String,String> cols,String separator){
		jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
		String content = new BaseTools().base64Decode(formContent);
		JSONArray jsonArray = JSONArray.fromObject(content,jsonConfig);
		int size = 0;
		if( jsonArray != null && (size = jsonArray.size()) > 0){
			List<String> colNames = new ArrayList<String>();
			if( cols != null) {
				for (Map.Entry<String, String> col : cols.entrySet()) {
					colNames.add( col.getKey() + separator + col.getValue());
				}
			}
			for (int i = 0; i < size; i++) {
				JSONObject jsonObject = JSONObject.fromObject(jsonArray.get(i), jsonConfig);
				String name = jsonObject.getString("attrName");
				if( name == null || name.length() == 0){
					name = jsonObject.getString("attrHiddenName");
				}
				//不需要导入的字段排除掉（因为name比较唯一，因此用作区分）
				if( exclude == null || !exclude.contains(name) ){
					String lable = jsonObject.getString("label");
					colNames.add((lable + separator + name).replace("ciDto.", ""));
				}
			}
			return removeEmptyString(colNames.toArray(new String[colNames.size()]));
		}
		return null;
	}
	/**
	 * 移除数组中的空白元素
	 * @param src
	 * @return
	 */
	public static String[] removeEmptyString(String[] src){
		if( src != null && src.length > 0 ){
			List<String> result = new ArrayList<String>();
			for (String string : src) {
				if( string != null && string.length() > 0){
					result.add(string);
				}
			}
			return result.toArray(new String[result.size()]);
		}
		return src;
	}
}
